package OOPAndMultiThreadArchiveManager.Server.Services;

import OOPAndMultiThreadArchiveManager.Server.Controllers.FileDownloadController;
import OOPAndMultiThreadArchiveManager.Server.Tools.PropertiesLoader;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;

public class FileDownloadService extends Thread {
    private ExecutorService cacheThreadPool;

    public FileDownloadService(ExecutorService cacheThreadPool) {
        this.cacheThreadPool = cacheThreadPool;
    }
    @Override
    public void run() {
        ServerSocket serverSocket = null;
        try {
            var port = PropertiesLoader.FileDownloadPort;
            serverSocket = new ServerSocket(port);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        while (true) {
            Socket socket = null;
            try {
                socket = serverSocket.accept();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
            try {
                var task = new FileDownloadController(socket);
                cacheThreadPool.submit(task);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }
}
